import 'package:OASys/api/MenuApi.dart';
import 'package:OASys/api/RoleApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/MenuVo.dart';
import 'package:OASys/entity/RoleVo.dart';
import 'package:flutter/material.dart';

class RoleEditPage extends StatelessWidget {
  final Map arguments;

  RoleEditPage({Key key, this.arguments});

  @override
  Widget build(BuildContext context) {
    if (arguments == null) {
      return ScaffoldItem('角色管理', MyRoleEditPage());
    }
    return ScaffoldItem(
        '角色管理',
        MyRoleEditPage(
          roleVo: RoleVo.fromJson(arguments),
        ));
  }
}

class MyRoleEditPage extends StatefulWidget {
  final RoleVo roleVo;

  MyRoleEditPage({Key key, this.roleVo});

  @override
  _MyRoleEditPageState createState() => _MyRoleEditPageState();
}

class _MyRoleEditPageState extends State<MyRoleEditPage> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  List<MenuVo> menuList;
  int menuListLength = 0;
  RoleVo info = new RoleVo();
  List<bool> boolList = [];

  bool test = false;

  @override
  void initState() {
    super.initState();
    if (widget.roleVo != null) {
      info = RoleVo.fromJson(widget.roleVo.toJson());
    }
    getMenuList();
  }

  // 构建权限选项列表
  void buildBoolList(List<MenuVo> menus) {
    if (menus == null || menus.length == 0) {
      boolList = [];
      for (int index = 0; index < menuList.length; index++) {
        boolList.add(false);
      }
    } else {
      print('add');
      boolList = [];
      List<int> indexList = [];
      for (int menusIndex = 0; menusIndex < menus.length; menusIndex++) {
        int index = itemIndexOf(menus[menusIndex], menuList);
        print(index);
        if (index > -1) {
          print(index);
          indexList.add(index);
        }
      }
      for (int index = 0; index < menuList.length; index++) {
        if (indexList.indexOf(index) > -1) {
          boolList.add(true);
        } else {
          boolList.add(false);
        }
      }
    }
  }

  // 查询item在list中的位置
  int itemIndexOf(MenuVo item, List<MenuVo> list) {
    for (int index = 0; index < list.length; index++) {
      if (item.id == list[index].id) {
        return index;
      }
    }
    return -1;
  }

  // 获取权限列表
  void getMenuList() {
    MenuApi().list(
      success: (res) {
        setState(() {
          menuList = res;
          menuListLength = res.length;
          if (info.menuList == null || info.menuList.length == 0) {
            buildBoolList(null);
          } else {
            buildBoolList(info.menuList);
          }
        });
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 表单保存操作
  void save() {
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
      print(info.toJson().toString());
      print(boolList.toString());
      List<int> menuIds = [];
      for (int index = 0; index < boolList.length; index++) {
        if (boolList[index]) {
          menuIds.add(menuList[index].id);
        }
      }
      print(menuIds.toString());
      doSave(info, menuIds);
    }
  }

  // 保存操作
  void doSave(RoleVo info, List<int> ids) {
    RoleApi().save(
      info,
      ids,
      success: (res) {
        Navigator.of(context).pop(true);
        showSuccessMessage(context);
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 表单重置操作
  void reset() {
    var form = formKey.currentState;
    form.reset();
    setState(() {
      if (widget.roleVo != null) {
        info.status = int.parse(widget.roleVo.status.toString());
        buildBoolList(info.menuList);
      } else {
        info.status = 1;
        buildBoolList(null);
      }
    });
  }

  // 构建权限选项
  Widget buildMenuItem(int index) {
    return Container(
      width: 100,
      child: CheckboxListTile(
        title: Text(menuList[index].name),
        value: this.boolList[index],
        onChanged: (bool value) {
          setState(() {
            print(this.boolList[index]);
            this.boolList[index] = value;
          });
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 900,
      width: 400,
      margin: EdgeInsets.all(45),
      child: Card(
        child: Container(
          margin: EdgeInsets.all(20),
          child: Form(
            key: formKey,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    PrefixContanier('角色名：'),
                    FormInput(
                      initValue: info.name,
                      hintText: "请输入角色名",
                      validator: (content) {
                        if (content.length > 12) {
                          return "用户名过长";
                        } else if (content.length <= 0) {
                          return "用户名过短";
                        }
                      },
                      onSave: (value) {
                        info.name = value;
                      },
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    PrefixContanier('状态：'),
                    Text(info.status == 0 ? '启用' : '禁用'),
                    Switch(
                      value: info.status == 0,
                      activeColor: Colors.green,
                      inactiveTrackColor: Colors.red,
                      onChanged: (value) {
                        setState(() {
                          info.status = value ? 0 : 1;
                        });
                      },
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    PrefixContanier('权限：'),
                    Container(
                      width: 200,
                      height: 200,
                      child: ListView.builder(
                        itemCount: menuListLength,
                        itemBuilder: (BuildContext context, int index) {
                          return buildMenuItem(index);
                        },
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 30,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    RaisedButton(
                      color: Color.fromRGBO(33, 150, 243, 1),
                      onPressed: save,
                      child: Text(
                        "保 存",
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    RaisedButton(
                      color: Color.fromRGBO(103, 194, 58, 1),
                      onPressed: reset,
                      child: Text(
                        "重 置",
                        style: TextStyle(color: Colors.white),
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
